package im

import (
    "fmt"
	"encoding/json"
	"dhfshop/controllers/base"
	"thirdpaysdk/api/hnapay"
	"dhfshop/domain/im"
	//"dhfshop/models/isv"
	"dhfshop/domain/pay"
	"dhfshop/service/redisgo"
	"github.com/astaxie/beego"
)

type HnaPayController struct {
	base.BaseController
}

func (this *HnaPayController) HnaPayNotify() {
	notifyData := this.Ctx.Input.RequestBody
	beego.Debug("HnaPayNotify notifyData:", string(notifyData))
	//
	msg := this.GetString("msg")
	merCode,orderId,sign,rspMap,err := hnapay.PreParseHnapay(msg)
	if err != nil {
	   beego.Debug("PreParseHnapay error:", err.Error())
	   return
	}
	beego.Debug("merCode:",merCode,"orderId:",orderId)
	var payInfoCache *paylayer.PayInfoCache = new(paylayer.PayInfoCache)
	cacheKey := "payorder_" + orderId
	redisconn := redisgo.GetInstance()
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 5  {
	    //beego.Debug("cache pay info:", cacheValue)
		if err = json.Unmarshal([]byte(cacheValue), payInfoCache); err == nil {
			
		}
	}else{
	    beego.Debug("cache pay info err:", err.Error())
		return 
	}
	err = hnapay.VerifyHnapaySign(msg,sign,payInfoCache.AppKey)
	if err != nil {
	   beego.Debug("VerifyHnapaySign error:", err.Error())
	   return
	}
	reqMap := make(map[string]string)
	for k, v := range rspMap {
		reqMap[k] = fmt.Sprintf("%v", v)
	}
	reqMap["LocalKind"] = "HNAPAY_NOTIFY"
	reqMap["attach"] = payInfoCache.OrderKind
	imlayer.PushMsgSvrIns.PushDao <- &reqMap
	//
	this.Ctx.WriteString("SUCCESS")
	return
}
